package com.itheima;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/servletDemo1")
public class ServletDemo1 extends HttpServlet {
   @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       boolean flag=false;
       resp.setContentType("text/html;charset=UTF-8");
       PrintWriter pw = resp.getWriter();
       Cookie[] arr = req.getCookies();
       String value=null;
       for (Cookie c : arr) {
           if("time".equals(c.getName())){
               flag=true;
               value = c.getValue();
               break;
           }
       }
       if(flag){
           pw.write("欢迎使用本网站，你的最后访问时间为：<br/>");
           SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           pw.write(sdf.format(new Date(Long.parseLong(value))));
       }else {
           pw.write("欢迎使用本网站，你为第一次访问：<br/>");
       }
       Cookie cookie=new Cookie("time",System.currentTimeMillis()+"");
       cookie.setMaxAge(300);
       resp.addCookie(cookie);
   }

   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req,resp);
   }
}
